package com.huxiu.yd;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.DiscoveryListResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/23:下午10:19.
 */
public class SearchActivity extends BaseActivity
        implements View.OnClickListener, AdapterView.OnItemClickListener,
        OnRefreshListener2<ListView> {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;
//
//    @InjectView(R.id.search_prompt_container)
//    FrameLayout searchPromptContainer;

    @InjectView(R.id.search_edit)
    EditText searchEdit;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    @InjectView(R.id.empty)
    TextView empty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        title.setText(R.string.search);
//        searchPromptContainer.setOnClickListener(this);
        searchEdit.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH && !TextUtils
                        .isEmpty(searchEdit.getText().toString())) {
                    list.setState(State.INIT_REFRESHING, true);
                    return true;
                }
                return false;
            }
        });
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
        list.setOnRefreshListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
//            case R.id.search_prompt_container:
//                searchPromptContainer.setVisibility(View.GONE);
//                searchEdit.setVisibility(View.VISIBLE);
//                searchEdit.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        searchEdit.requestFocus();
//                        showSoftKeyboard();
//                    }
//                }, 200);
//                break;
        }
    }

    private void showSoftKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.showSoftInputFromInputMethod(searchEdit.getWindowToken(), InputMethodManager
                .SHOW_FORCED);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DiscoveryItem item = items.get(position - 1);
        Intent intent = new Intent(this, DiscoveryDetailActivity.class);
        intent.putExtra(Constants.DISCOVERY_ITEM_KEY, item.toString());
        startActivity(intent);
    }

    private List<DiscoveryItem> items = new ArrayList<>();

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getSearchResult(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        getSearchResult(currentPage + 1);
    }

    private SearchResultAdapter adapter = new SearchResultAdapter();

    class SearchResultAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public DiscoveryItem getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder holder;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.search_result_list_item, parent, false);
                holder = new ViewHolder(view);
                view.setTag(holder);
            }
            holder = (ViewHolder) view.getTag();
            DiscoveryItem item = getItem(position);
            ImageLoader.getInstance()
                    .displayImage(item.image, holder.image, ImageUtils.getProductDisplayOption
                            (item.getProductPlaceHolder()));
            holder.searchResultTitle.setText(item.title);
            holder.searchResultAuthor.setText(item.name);
            holder.searchResultTime.setText(Utils.getDateString(item.create_time));
            return view;
        }
    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file
     * 'search_result_list_item.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers
     *         (http://github.com/avast)
     */
    static class ViewHolder {

        @InjectView(R.id.image)
        ImageView image;

        @InjectView(R.id.search_result_title)
        TextView searchResultTitle;

        @InjectView(R.id.search_result_author)
        TextView searchResultAuthor;

        @InjectView(R.id.search_result_time)
        TextView searchResultTime;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private int currentPage = 0;

    private void getSearchResult(final int page) {
        String url = NetworkConstants.DISCOVERY_URL;
        Map<String, String> params = new HashMap<>();
        params.put("act", "search");
        params.put("search_key", searchEdit.getText().toString());
        params.put("page", Integer.toString(page));
        GsonRequest<DiscoveryListResponse> request = new GsonRequest<>(url, Method.POST,
                DiscoveryListResponse.class, false, params, new Listener<DiscoveryListResponse>() {
            @Override
            public void onResponse(DiscoveryListResponse response) {
                list.setEmptyView(empty);
                if (response.isSuccess()) {
                    if (page == 0) {
                        items.clear();
                    }
                    Collections.addAll(items, response.data);
                    adapter.notifyDataSetChanged();
                    currentPage = response.page;
                    refreshComplete();
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
    }

    private void refreshComplete() {
        list.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.onRefreshComplete();
            }
        }, 100);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context
                .INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(list.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    protected ErrorListener mErrorListener = new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dismissProgress();
            Throwable t = error.getCause();
            list.setEmptyView(empty);
            if (t instanceof ErrorResponseException) {
                Utils.showToast(error.getMessage());
                items.clear();
                adapter.notifyDataSetChanged();
            } else {
                Utils.showToast(R.string.generic_failure);
            }
            refreshComplete();
        }
    };

}
